<template>
	<view class="cal">
		<view class="cal-top" v-if="isShowYear">
			<view class="prev" @click="changeWeek('prev')" v-if="prevActive">上一周</view>
			<text class="date" ref="t1">{{ nowSelectDateString }}</text>
			<view class="next" @click="changeWeek('next')" v-if="prevActive">下一周</view>
		</view>

		<view class="cal-content">
			<view class="cal-ul cal-weeks">
				<view class="cal-li text" v-for="(item, i) of baseData.weekTitles" :key="i">
					<text>{{ item }}</text>
				</view>
			</view>

			<swiper :current="current" ref="calSwiper" class="cal-swiper" :duration="200" circular
				@animationfinish="swiperFisnish">
				<swiper-item v-for="(days, i) of weeks" :key="i">
					<view class="cal-ul cal-days">
						<view class="cal-li" v-for="(item, j) of days" :key="j" @click="changeSelected(item)">
							<view class="cal-day-li" :class="{ 'cal-day-li-selected': item.timeSpan == baseData.selectedDate.timeSpan }">
								<text :class="item.isHasData ? 'hasData' : 'noData'">{{ isToday(item.m)?'今':item.d }}</text>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<pgb-tabbar ref="t2"></pgb-tabbar>
	</view>
</template>


<script setup lang="ts">
/**
 * weekCalendar 周日历选择组件
 * @description 日历选择某一天的组件
 * @bug 因是使用swiper组件开发快速滑动多屏 无法触发 @animationfinish 导致展示异常
 * @property {Number} defaultDate 默认时间时间戳
 * @event {Function} changeDate 当前选中日期发生改变
 * @example <chenmushan-week-calendar @changeDate="changeDate"></chenmushan-week-calendar>
 */
import { ref, reactive, computed, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
const props = defineProps({
	defaultDate: { type: Number, default: 0 },   // 默认值 必须是数组
	isShowYear: { type: Boolean, default: true },   // 默认值 是否显示年标题
	prevActive: { type: Boolean, default: true },   // 默认值 必须是数组
	nextActive: { type: Boolean, default: true },   // 默认值 必须是数组
	busData: { type: Array, default: [] },   // 默认值 必须是数组 业务数据，控制显示
	month: { type: String, default: '' },   // 默认值 月份
})
const emit = defineEmits(['changeDate', 'swiperFisnish'])
const weeks: any = ref([]);
const propDate: any = ref(null);
const current = ref(0);
const baseData: any = reactive({
	weekTitles: ['一', '二', '三', '四', '五', '六', '日',],
	current: 0,
	selectedDate: {
		d: null, // 在当前月份中的天
		ym: '', // 年月拼接
		timeSpan: 0 // 时间戳
	}
})

const isToday=(val: any)=>{
	return dayjs(val).format('YYYY-MM-DD').valueOf() === dayjs(new Date()).format('YYYY-MM-DD').valueOf()
}
onLoad(() => {
	propDate.value = props.defaultDate == 0 ? new Date() : new Date(props.defaultDate);
	// initData();
})
const initData = () => {
	let lastSat = new Date(propDate.value);

	baseData.selectedDate = {
		d: lastSat.getDate(),
		ym: `${lastSat.getFullYear()}${lastSat.getMonth() + 1}`,
		timeSpan: +lastSat,
		m: new Date(lastSat)
	};

	// 寻找到距离当前日期最近的周六
	while (lastSat.getDay() != 0) lastSat.setDate(lastSat.getDate() + 1);
	weeks.value[0] = getWeekDaysByLastSat(lastSat);
	weeks.value[1] = getWeekDaysByWeeks(weeks.value[0], true);
	weeks.value[2] = getWeekDaysByWeeks(weeks.value[0], false);
	current.value = 0;
	console.log('weeksinit', weeks)
}
const changeWeeksByMonthChange = function (val: any) {
	let lastSat = new Date(val);

	// baseData.selectedDate = {
	// 	d: lastSat.getDate(),
	// 	ym: `${lastSat.getFullYear()}${lastSat.getMonth() + 1}`,
	// 	timeSpan: +lastSat,
	// 	m: new Date(lastSat)
	// };

	// 寻找到距离当前日期最近的周六
	while (lastSat.getDay() != 0) lastSat.setDate(lastSat.getDate() + 1);
	weeks.value[0] = getWeekDaysByLastSat(lastSat);
	weeks.value[1] = getWeekDaysByWeeks(weeks.value[0], true);
	weeks.value[2] = getWeekDaysByWeeks(weeks.value[0], false);

	console.log('current.value', current.value)
	current.value = 0;
	// changeWeeks(false,0)
	console.log('weeks', weeks)
}
defineExpose({
	changeWeeksByMonthChange,
})
const swiperFisnish = (e: any) => {
	let current1 = e.detail.current;
	console.log('current.value11111', current1, current.value,weeks.value[current1])
	current.value = current1
	changeWeeks(current1 > baseData.current, current1);
	// baseData.upCurrIndex = current1;
	// baseData.selectedDate = weeks.value[current1][0]

	emit('swiperFisnish' , weeks.value[current1][0])
}
const changeWeeks = (direction: any, current: any) => {
	let nextIndex = current + 1 > 2 ? 0 : current + 1;
	let prevIndex = current - 1 < 0 ? 2 : current - 1;
	weeks.value[nextIndex] = getWeekDaysByWeeks(weeks.value[current], true);
	weeks.value[prevIndex] = getWeekDaysByWeeks(weeks.value[current], false);
}
// 修改周时间
const changeWeek = (type: any) => {
	let current1 = current.value;
	let nextIndex = current1 + 1 > 2 ? 0 : current1 + 1;
	let prevIndex = current1 - 1 < 0 ? 2 : current1 - 1;
	if (type == 'prev') {
		current.value = prevIndex;
	} else {
		current.value = nextIndex;
	}
}
// 通过周六数据获取一周的数据
const getWeekDaysByLastSat = (lastSat: any) => {
	lastSat = new Date(lastSat);
	let reuslt: any = [];

	for (var i = 0; i < 7; i++) {
		reuslt.push({
			d: lastSat.getDate(),
			ym: `${lastSat.getFullYear()}${lastSat.getMonth() + 1}`,
			timeSpan: +lastSat,
			m: new Date(lastSat)
		});

		lastSat.setDate(lastSat.getDate() - 1);
	}

	return reuslt.reverse();
}
// 通过一周的数据获取本周的上周或下周
const getWeekDaysByWeeks = (weeks: any, direction: any) => {
	// 下周
	if (direction) {
		let nextLastSat = new Date(weeks[weeks.length - 1].timeSpan);
		nextLastSat.setDate(nextLastSat.getDate() + 7);
		return getWeekDaysByLastSat(nextLastSat);
	}
	// 上周
	else {
		let prevLstSat = new Date(weeks[0].timeSpan);
		prevLstSat.setDate(prevLstSat.getDate() - 1);
		return getWeekDaysByLastSat(prevLstSat);
	}
}
// 修改当前选中
const changeSelected = (item: any) => {
	console.log('item::', item);
	if(!item.isHasData){
		return false;
	}
	if (baseData.selectedDate.timeSpan != item.timeSpan) {
		baseData.selectedDate = {
			...item,
			m: new Date(item.timeSpan)
		};

		emit('changeDate', baseData.selectedDate);
	}
}
const nowSelectDateString = computed(() => {
	let m = baseData.selectedDate.m;
	return m ? `${m.getFullYear()}年${m.getMonth() + 1}月${m.getDate()}日` : '';
})

watch(() => props.defaultDate,
	async (newVal, oldVal) => {
		propDate.value = props.defaultDate == 0 ? new Date() : new Date(props.defaultDate);
		initData();
	},
	{ immediate: true }
);
watch(() => props.busData,
	async (newVal, oldVal) => {
		// propDate.value = props.defaultDate == 0 ? new Date() : new Date(props.defaultDate);
		// initData();
		newVal.forEach((item: any) => {
			weeks.value.forEach((itemWeek: any) => {
				itemWeek.forEach((day: any) => {
					if (dayjs(day.m).format('YYYY-MM-DD') === item.name) {
						day.isHasData = item.value
					}
				})
			})
		})
	},
	{ immediate: true }
);
// watch(() => props.month,
// 	async (newVal, oldVal) => {
// 		if (newVal) {
// 			changeWeeksByMonthChange(newVal + '-01')
// 		}
// 	},
// 	{ immediate: true }
// );
</script>

<style lang="scss" scoped>
.cal {
	height: 160rpx;
	background: #0000a6;
	margin: 0 auto;
	border-radius: 30rpx;
	overflow: hidden;
}

.cal-top {
	position: relative;
	height: 91rpx;
	background: #3ea3ff;
	border-radius: 30rpx 30rpx 0rpx 0rpx;
	line-height: 91rpx;
	text-align: center;
	// display: flex;
	// justify-content: space-between;
	box-sizing: border-box;
	padding: 0 30rpx;

	.prev,
	.next {
		color: #ffffff;
		font-size: 26rpx;
	}

	.prev {
		float: left;
	}

	.next {
		float: right;
	}

	.date {
		position: absolute;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 34rpx;
		font-weight: bold;
		color: #ffffff;
		pointer-events: none;
	}
}

.cal-content {
	padding: 15rpx 0 40rpx;
}

.cal-swiper {
	margin-top: 20rpx;
}

.cal-ul {
	position: relative;
	display: flex;
	justify-content: space-between;

	.cal-li {
		width: calc(100% / 7);
		text-align: center;
	}
	.text{
		height: 40rpx;
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 40rpx;
	}
}

.cal-weeks {
	font-size: 28rpx;
	font-weight: 700;
	color: #3ea3ff;
}

.cal-days {
	font-size: 30rpx;
	color: #333;
}

.cal-day-li {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 63rpx;
	height: 63rpx;
	margin: 0 auto;

	.hasData {
		color: #ffffff;
		width: 100%;
		text-align: center;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		font-size: 36rpx;
	}

	.noData {
		color: rgba(255, 255, 255, 0.3);
		width: 100%;
		text-align: center;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		font-size: 36rpx;
	}
}

.cal-day-li-selected {
	// background-color: #3ea3ff;
	// border-radius: 50%;
	color: #fff !important;
	box-sizing: border-box;
	border-radius: 12rpx;
	font-weight: 500;
	border: 2rpx solid #FFFFFF;
	background:rgba(255,255,255,0.25);
}
</style>
